﻿@page "/auth"

<Loading />

@code {
    /// <summary>
    /// 初始化
    /// </summary>
    /// <returns></returns>
    protected override async Task OnInitializedAsync()
    {
        // localStorage中access_token值
        var access_token = await Common.GetStorageAsync("access_token");

        // access_token有值
        if (!string.IsNullOrEmpty(access_token))
        {
            // 获取token
            var _token = await Http.GetFromJsonAsync<ServiceResult<string>>($"/auth/token?access_token={access_token}");
            if (_token.Success)
            {
                // 将token存入localStorage
                await Common.SetStorageAsync("token", _token.Result);

                // 跳转至后台首页
                await Common.NavigateTo("/admin");
            }
            else
            {
                // access_token失效，或者请求失败的情况下，重新执行一次验证流程
                await AuthProcessAsync();
            }
        }
        else //access_token为空
        {
            await AuthProcessAsync();
        }
    }

    /// <summary>
    /// 验证流程
    /// </summary>
    /// <returns></returns>
    private async Task AuthProcessAsync()
    {
        // 当前URI对象
        var uri = await Common.CurrentUri();

        // 是否回调携带了code参数
        bool hasCode = QueryHelpers.ParseQuery(uri.Query).TryGetValue("code", out Microsoft.Extensions.Primitives.StringValues code);

        if (hasCode)
        {
            var access_token = await Http.GetFromJsonAsync<ServiceResult<string>>($"/auth/access_token?code={code}");
            if (access_token.Success)
            {
                // 将access_token存入localStorage
                await Common.SetStorageAsync("access_token", access_token.Result);

                var token = await Http.GetFromJsonAsync<ServiceResult<string>>($"/auth/token?access_token={access_token.Result}");
                if (token.Success)
                {
                    // 将token存入localStorage
                    await Common.SetStorageAsync("token", token.Result);

                    // 成功认证授权，跳转至后台管理首页
                    await Common.NavigateTo("/admin");
                }
                else
                {
                    // 没有权限的人，回到首页去吧
                    await Common.NavigateTo("/");

                    // 输出提示信息
                    Console.WriteLine(token.Message);
                }
            }
            else
            {
                // 出错了，回到首页去吧
                await Common.NavigateTo("/");

                // 输出提示信息
                Console.WriteLine(access_token.Message);
            }
        }
        else
        {
            // 获取第三方登录地址
            var loginAddress = await Http.GetFromJsonAsync<ServiceResult<string>>("/auth/url");

            // 跳转到登录页面
            await Common.NavigateTo(loginAddress.Result);
        }
    }
}